package com.xnfh.home.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.view.get
import androidx.recyclerview.widget.GridLayoutManager
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.SmartGlideImageLoader
import com.xnfh.common.adapter.SelectImageAdapter
import com.xnfh.common.utils.FullyGridLayoutManager
import com.xnfh.common.utils.GlideEngine
import com.xnfh.framework.Constants
import com.xnfh.framework.base.BaseActivity
import com.xnfh.framework.base.BaseStateObserver
import com.xnfh.framework.bean.FeedBackFieldBean
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast
import com.xnfh.home.R
import com.xnfh.home.databinding.ActivityFeedbackBinding
import com.xnfh.home.viewmodel.FeedBackViewModel

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2024/1/4 15:15
 * @UpdateUser: ziheng
 * @UpdateDate: 2024/1/4 15:15
 * @UpdateRemark: 更新说明
 */
class FeedBackActivity : BaseActivity<ActivityFeedbackBinding>(), View.OnClickListener {
    override fun getLayoutID(): Int = R.layout.activity_feedback

    companion object {
        fun start(context: Context, bundle: Bundle? = null) {
            val intent = Intent(context, FeedBackActivity::class.java)
            bundle?.let {
                intent.putExtra("bundle", it)
            }
            context.startActivity(intent)
        }
    }

    //反馈类型
    private var feedbackType: Int? = null
    private lateinit var viewModel: FeedBackViewModel
    private var selectFieldId: String? = null
    private var provinceId: String? = null
    private var cityId: String? = null
    private var districtId: String? = null
    private var cropId: Int? = null//作物id

    /**
     * 打开选择图片的页面
     */
    private var photoList = ArrayList<Photo>()
    private var imageAdapter: SelectImageAdapter? = null

    override fun init() {
        setHeaderTitle(getString(R.string.str_feedback))
        mBind.feedbackSelectField.setOnClickListener(this)
        mBind.feedbackSubmit.setOnClickListener(this)
        val bundle = intent.getBundleExtra("bundle")
        feedbackType = bundle?.getInt("id")
        //设置选择图片的recycle
        val fullyGridLayoutManager =
            FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
        mBind.feedbackRecyclerBitmap.layoutManager = fullyGridLayoutManager
        imageAdapter = SelectImageAdapter(3)
        imageAdapter?.setNewInstance(null)//先设置一个null，内部会处理添加➕的图片
        mBind.feedbackRecyclerBitmap.adapter = imageAdapter
        imageAdapter?.setCallBack(object : SelectImageAdapter.SelectImageCallBack {
            /**
             * 选择图片
             */
            override fun addImageClick() {
                openPic()
            }

            /**
             * 查看大图
             */
            override fun showBigImage(position: Int, imageView: ImageView) {
                XPopup.Builder(this@FeedBackActivity).asImageViewer(
                    imageView, position,
                    imageAdapter?.data?.toMutableList() as List<Any>?,
                    { popupView, position ->
                        popupView.updateSrcView(mBind.feedbackRecyclerBitmap[position].findViewById(com.xnfh.common.R.id.item_select_image_view) as ImageView)
                    }, SmartGlideImageLoader()
                ).show()
            }

            /**
             * 删除指定图片
             */
            override fun deleteImagePosition(position: Int) {
                photoList.removeAt(position)
            }
        })
    }

    override fun onClick(v: View?) {
        when (v) {
            mBind.feedbackSelectField -> {
                viewModel.requestFeedBackFieldList()
            }

            mBind.feedbackSubmit -> {
                if (selectFieldId.isNullOrBlank()) {
                    TipsToast.showTips(R.string.str_place_select_dk_tips)
                    return
                }
                viewModel.requestFeedBack(photoList,cropId,selectFieldId,provinceId,cityId,districtId,feedbackType,mBind.feedbackConnectEdit.text.toString())
            }
        }
    }

    override fun observe() {
        viewModel = FeedBackViewModel()
        viewModel.fieldList.observe(this, object : BaseStateObserver<List<FeedBackFieldBean>>() {
            override fun getRespDataSuccess(it: List<FeedBackFieldBean>) {
                super.getRespDataSuccess(it)
                if(it.isEmpty()){
                    TipsToast.showTips(R.string.str_no_field)
                    return
                }
                val popDataList = ArrayList<String>()
                it.forEach {
                    popDataList.add(it.udfName)
                }
                XPopup.Builder(this@FeedBackActivity) //.maxWidth(600)
                    .asCenterList(
                        "请选择一项", popDataList.toTypedArray()
                    ) { position, text ->
                        selectFieldId = it[position].dautoid
                        provinceId = it[position].proviceId
                        cityId = it[position].cityId
                        districtId = it[position].districtId
                        cropId = it[position].udcId
                        mBind.feedbackSelectField.text = text
                    }
                    .show()
            }
        })
    }

    private fun openPic() {
        EasyPhotos.createAlbum(
            this,
            true,
            false,
            GlideEngine.get()
        )//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
            .setFileProviderAuthority(Constants.SELECT_PIC)//参数说明：见下方`FileProvider的配置`
            .setCount(3)
            .setSelectedPhotos(photoList)
            .start(object : SelectCallback() {
                override fun onResult(photos: java.util.ArrayList<Photo>?, isOriginal: Boolean) {
                    photoList.clear()
                    photos?.let { photoList.addAll(it) }
                    val list = ArrayList<String>()
                    if (photos != null && photos.size > 0) {
                        photos.forEach {
                            list.add(it.path)
                        }
                    }
                    imageAdapter?.setNewInstance(list)
                }

                override fun onCancel() {
                    LogUtil.d("取消选择图片回调")
                }

            })
    }

}